import 'package:chengyu/global.dart';
import 'package:chengyu/http/api.dart';
import 'package:chengyu/page/detail.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class IndexPage extends StatefulWidget {
  IndexPage({Key key, this.data}) : super(key: key);
  final data;

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  List resouItems = [];
  List resultItems = [];
  TextEditingController _searchController = new TextEditingController();

  @override
  void initState() {
    EasyLoading.show(status: '');
    getResouChengyu().then((res) {
      EasyLoading.dismiss();
      setState(() {
        resouItems = res['items'];
      });
    });
    super.initState();
  }

  search(key) {
    if (key != null && key.trim() != '') {
      EasyLoading.show(status: '搜索中...');
      searchChengyuByKey(key).then((res) {
        EasyLoading.dismiss();
        if (res == null || res['result'].length == 0) {
          EasyLoading.showToast('匹配不到关键词，试试其他成语吧');
        }
        setState(() {
          resultItems = res['result'];
        });
      });
    }
  }

  List<Widget> renderResouChengyuTag(tags) {
    List<Widget> items = [];
    for (var i = 0; i < tags.length; i++) {
      var item = tags[i];
      if (item['name'].length < 5) {
        items.add(InkWell(
          child: Container(
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Global.fontSecondColor.withOpacity(0.2),
                  width: 0.5,
                ),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  item['name'],
                  style: TextStyle(
                    color: Global.fontColor,
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      '查看详情',
                      style: TextStyle(
                        color: Global.fontSecondColor.withOpacity(0.7),
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    Icon(
                      Icons.chevron_right,
                      color: Global.fontSecondColor,
                      size: 13,
                    )
                  ],
                ),
              ],
            ),
          ),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => DetailPage(id: item['id']),
              ),
            );
          },
        ));
      }
    }

    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          width: MediaQuery.of(context).size.width,
          height: 200,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Global.primaryColor,
                Global.primaryColor.withOpacity(0.3),
              ],
            ),
          ),
          child: Stack(
            children: [
              Positioned(
                left: 0,
                bottom: 0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  child: Image.asset('assets/images/cloud1.png'),
                ),
              ),
              Positioned(
                left: 0,
                bottom: 0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  child: Image.asset('assets/images/cloud2.png'),
                ),
              ),
              Positioned(
                left: 20,
                right: 20,
                bottom: 90,
                child: Container(
                  padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                  width: MediaQuery.of(context).size.width,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Global.backgroundColor,
                      width: 0.5,
                    ),
                    borderRadius: BorderRadius.circular(30),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextField(
                          controller: _searchController,
                          keyboardType: TextInputType.text,
                          decoration: InputDecoration.collapsed(
                            hintText: "搜索成语",
                            hintStyle: TextStyle(
                              color: Global.backgroundColor,
                              fontSize: 13,
                            ),
                          ),
                          onSubmitted: (text) {
                            search(text);
                          },
                        ),
                      ),
                      Container(
                        width: 50,
                        height: 30,
                        child: ClipRRect(
                          borderRadius: BorderRadius.all(Radius.circular(40)),
                          child: FlatButton(
                            color: Global.backgroundColor,
                            onPressed: () {
                              search(_searchController.text.toString());
                            },
                            child: Icon(
                              Icons.search,
                              color: Global.primaryColor.withOpacity(0.7),
                              size: 20,
                            ),
                            textColor: Global.backgroundColor,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        Expanded(
          child: Container(
            padding: EdgeInsets.all(10),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    width: MediaQuery.of(context).size.width,
                    child: Center(
                      child: Text(
                        resultItems.length > 0 ? '搜索结果' : '',
                        style: TextStyle(
                          color: Global.primaryColor.withOpacity(0.6),
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                  Column(
                    children: renderResouChengyuTag(resultItems),
                  ),
                  SizedBox(height: 10),
                  Container(
                    width: MediaQuery.of(context).size.width,
                    child: Center(
                      child: Text(
                        '热门搜索',
                        style: TextStyle(
                          color: Global.primaryColor.withOpacity(0.6),
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                  Column(
                    children: renderResouChengyuTag(resouItems),
                  ),
                ],
              ),
            ),
          ),
        ),
        SizedBox(height: 20)
      ],
    );
  }
}
